package team.qwer.demo.common.util.httpservletwrapper;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class RequestWrapper extends HttpServletRequestWrapper {


    private final ByteArrayOutputStream cacheStream;

    private final ByteArrayInputStream inputStream;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        cacheStream = new ByteArrayOutputStream();
        int length = 1024;
        byte[] byteBuffer = new byte[1024];
        while ((length = request.getInputStream().read(byteBuffer, 0, length)) != -1) {
            cacheStream.write(byteBuffer, 0, length);
        }
        inputStream = new ByteArrayInputStream(cacheStream.toByteArray());
    }

    @Override
    public ServletInputStream getInputStream() {
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() {
                return inputStream.read();
            }
        };
    }

    public ByteArrayOutputStream getCacheStream() {
        return this.cacheStream;
    }

}
